package com.teemor.im.remoting.instance;


import com.teemor.im.common.util.IOUtil;
import com.teemor.im.remoting.netty.SocketChooseHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

import java.net.InetSocketAddress;


/**
 * Netty 服务
 * Created by 尼恩 @ 疯狂创客圈
 */
public class WebSocketServer
{

    /**
     * 单例
     */
    private static WebSocketServer singleInstance = new WebSocketServer();

    private int port;

    public static WebSocketServer inst(int port)
    {
        singleInstance.port = port;
        return singleInstance;
    }


    private final EventLoopGroup group = new NioEventLoopGroup();
    private Channel channel;


    /**
     * 停止即时通讯服务器
     */
    public void stop()
    {
        if (channel != null)
        {
            channel.close();
        }

        group.shutdownGracefully();
    }

    /**
     * 启动即时通讯服务器
     */
    public void start()
    {
        ChannelFuture channelFuture = null;
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(group)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChatServerInitializer());
        InetSocketAddress address = new InetSocketAddress(port);
        String ip = IOUtil.getHostAddress();
        channelFuture = bootstrap.bind(address);
        try {
            channelFuture.sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 内部类
     */
    class ChatServerInitializer extends ChannelInitializer<Channel>
    {


        @Override
        protected void initChannel(Channel ch) throws Exception
        {
            ChannelPipeline pipeline = ch.pipeline();
            pipeline.addFirst(new SocketChooseHandler());

        }
    }
}
